<template>
  <main class="wss-container">
    <div class="label-box-content">
      <el-row :gutter="20" type="flex">
        <el-col :span="10">
          <NewCard title="我的订单" :isright="isright">
            <template slot="right">
              <div class="top_search">
                <el-input
                  size="mini"
                  placeholder="搜索订单"
                  v-model="ParamsObj.title"
                  @change="searchinput"
                  @keyup.enter.native="searchinput"
                >
                  <i class="el-icon-search el-input__icon" slot="suffix"> </i>
                </el-input>
              </div>
            </template>
            <div class="tabOne">
              <div
                class="tablist"
                :class="payStatus == 1 ? 'isActive' : ''"
                @click="waitpay"
              >
                <img src="~@/assets/images/dzf_icon_nor.png" class="imgnor" />
                <img src="~@/assets/images/dzf_icon_sel.png" class="imgsel" />
                <el-button round>待支付</el-button>
              </div>
              <div
                class="tablist"
                :class="payStatus == 2 ? 'isActive' : ''"
                @click="service"
              >
                <img src="~@/assets/images/fwz_icon_nor.png" class="imgnor" />
                <img src="~@/assets/images/fwz_icon_sel.png" class="imgsel" />
                <el-button round>服务中</el-button>
              </div>
              <div
                class="tablist"
                :class="payStatus == 3 ? 'isActive' : ''"
                @click="Completed"
              >
                <img src="~@/assets/images/ywc_icon_nor.png" class="imgnor" />
                <img src="~@/assets/images/ywc_icon_sel.png" class="imgsel" />
                <el-button round>已完成</el-button>
              </div>
            </div>
            <!-- 待支付 -->
            <div class="orderList" v-if="payStatus == 1">
              <ul v-if="contractList.length">
                <li
                  :class="{ active: list.id === currentActive }"
                  v-for="list in contractList"
                  :key="list.id"
                  @click="rowclick(list)"
                >
                  <h2>
                    <p>{{ list.title }}</p>
                    <!-- 项目如果支付过了不显示倒计时，其他的显示倒计时（支付过的项目有支付时间payTime） -->
                    <span style="display: flex" v-if="!list.payTime">
                      <DownTime
                        @EventTimeIsUp="TimeIsUp"
                        :time="list.minutes"
                      ></DownTime
                      >后订单关闭
                    </span>
                    <span v-else>未支付</span>
                  </h2>
                  <!-- <i class="firstWord">{{ getHanzi(list.title) }}</i> -->
                  <p class="coll_source">
                    {{ selecttype(list.type) }} · {{ list.createdTime }}
                  </p>
                </li>
              </ul>
              <!-- 暂无数据 -->
              <p class="forData" v-else>暂无订单</p>
            </div>

            <!-- 服务中 -->
            <div class="orderList" v-else-if="payStatus == 2">
              <ul v-if="contractList.length">
                <li
                  :class="{ active: list.id === currentActive }"
                  v-for="list in contractList"
                  :key="list.id"
                  @click="rowclick(list)"
                >
                  <h2>
                    <p>{{ list.title }}</p>
                    <span class="isSerive">服务中</span>
                  </h2>
                  <!-- <i class="firstWord">{{ getHanzi(list.title) }}</i> -->
                  <p class="coll_source">
                    {{ selecttype(list.type) }} · {{ list.createdTime }}
                  </p>
                </li>
              </ul>
              <!-- 暂无数据 -->
              <p class="forData" v-else>暂无订单</p>
            </div>

            <!-- 已完成 -->
            <div class="orderList" v-else>
              <ul v-if="contractList.length">
                <li
                  :class="{ active: list.id === currentActive }"
                  v-for="list in contractList"
                  :key="list.id"
                  @click="rowclick(list)"
                >
                  <h2>
                    <p>{{ list.title }}</p>
                    <span class="isOk">已完成</span>
                  </h2>
                  <!-- <i class="firstWord">{{ getHanzi(list.title) }}</i> -->
                  <p class="coll_source">
                    {{ selecttype(list.type) }} · {{ list.createdTime }}
                  </p>
                </li>
              </ul>
              <!-- 暂无数据 -->
              <p class="forData" v-else>暂无订单</p>
            </div>
          </NewCard>
        </el-col>
        <el-col :span="14">
          <div class="FeaturedContent" v-if="demandShow == 0">
            <FeaturedContent></FeaturedContent>
          </div>
          <div class="pay" v-else-if="demandShow == 1">
            <template v-if="orderinfo.type == '6'">
              <projectPay
                :orderinfo="orderinfo"
                v-if="projectIpaid"
              ></projectPay>
              <projectPayIpaid
                :project="project"
                :orderinfo="orderinfo"
                :step="step"
                :flow="flow"
                v-else
              ></projectPayIpaid>
            </template>
            <Pay
              v-else
              @EventchangeDemandShow="changeDemandShowFn"
              :getConsumptionapilistfn="getConsumptionapilistfn"
              :orderinfo="orderinfo"
            ></Pay>
          </div>

          <!-- 项目 ***************** -->
          <div class="details" v-else-if="demandShow == 2">
            <projectDetails
              :orderinfo="orderinfo"
              v-if="orderinfo.type == '6'"
            ></projectDetails>
            <Details :orderinfo="orderinfo" v-else></Details>
          </div>
          <div class="details" v-else-if="demandShow == 3">
            <projectDetails
              :orderinfo="orderinfo"
              v-if="orderinfo.type == '6'"
            ></projectDetails>
            <Complete :orderinfo="orderinfo" v-else></Complete>
          </div>
          <!-- 四大类的详情 -->
          <div class="details" v-else-if="demandShow == 4">
            <Completesfour
              :orderinfo="orderinfo"
              :listActive="detailBoughtShow"
            ></Completesfour>
          </div>
          <!-- 合同智审详情 -->
          <div class="details" v-else-if="demandShow == 5">
            <Contractreview :orderinfo="orderinfo"></Contractreview>
          </div>

          <!-- 项目 *****************end -->
        </el-col>
      </el-row>
    </div>
  </main>
</template>

<script>
import Compay from "@/BMViews/components/Compay/index.vue";
import Pay from "./Pay.vue";
import projectPay from "./projectPay.vue";
import projectPayIpaid from "@/BMViews/views/userCenter/homepage/Pay.vue";
import projectDetails from "./projectDetails.vue";
import Details from "./details.vue";
import NewCard from "@/wss/components/newCard.vue";
import Complete from "./completes.vue";
import Completesfour from "./completesfour.vue";
import Contractreview from "./concant/index.vue";

/* eslint-disable */
import DownTime from "@/components/downTime/index.vue";
import FeaturedContent from "../../../../components/FeaturedContent/index.vue";
import { timestampConversion } from "@/wss/utils/wss.js";
import { getProjectGetInfoApi } from "@/BMViews/api/doc/project.js";

function getDownTime(list) {
  let timer = setInterval(() => {
    list.minutes--;
    if (list.minutes == 0 || list.minutes < 0) {
      clearInterval(timer);
    }
  }, 1000);
}
import {
  getConsumptionapilist,
  getConsumptionapilistinfo,
} from "../../../api/myOrder/myOrder";

export default {
  name: "myOrder",

  components: {
    Compay,
    NewCard,
    Pay,
    Details,
    FeaturedContent,
    Complete,
    Completesfour,
    DownTime,
    projectPay,
    projectDetails,
    projectPayIpaid,
    Contractreview,
  },

  data() {
    return {
      currentActive: "",
      // 订单id
      orderNo: "",
      ParamsObj: {
        //用户id
        userId: this.$store.state.user.userId,
        status: 1, //默认为未选择
        title: "",
      },
      detailBoughtShow: 0,
      minutes: 15, //分
      seconds: 0, //，秒
      isright: true, //显示搜索框
      searchValue: "", //输入框的值

      payStatus: 1, //当前选择的类型 1待支付 3服务中 0已完成
      // 项目假数据
      projectInfo: {},
      // 订单列表
      contractList: [],
      projectIpaid: true, // 当前项目是初次的支付还是支付过了要支付别的步骤的状态
      project: {}, //项目支付过了要支付的下一步的数据
      step: [], //项目支付过了要支付的下一步的 步骤数据
      flow: {}, //项目支付过了要支付的下一步的 要支付的步骤

      demandShow: 0, //
      orderinfo: {}, //对应的id详细信息
      unpaidList: [],
      isRefresh: false,
    };
  },
  created() {
    this.$off("CountdownOff");
    this.getConsumptionapilistfn();
    // 监听是否支付
    this.$bus.$on("EventPaymentCompletion", () => {
      this.demandShow = 0;
    });
    this.$bus.$on("CountdownOff", () => {
      this.demandShow = 0;
    });

    //通过$bus跳转支付页面  this.project, this.orderinfo, this.step, flowId
    this.$bus.$on("handlerPay", (num, project, orderinfo, step, flow) => {
      this.demandShow = 1;
    });

    // 通过$bus 支付成功了，刷新列表并且显示推荐页面
     this.$bus.$on("skipFeat",()=>{
      this.getConsumptionapilistfn(); //刷新列表
      this.demandShow = 0;
    })
      //结案的回调
      this.$bus.$on("refreshclosOrder", (item) => {
      this.refreshclosOrder(item);
     
    });
  },
  filters: {
    getMinutes(list) {
      getDownTime(list);
      return list.minutes;
    },
  },
  methods: {
    // 项目如果支付过了不显示倒计时，其他的显示倒计时
    async isCountDown(list) {
      console.log("chufa");
      // 获取项目详情
      let nowdata = await this.getProjectGetInfo(list.goodsId);
      let state = true;
      // 有项目才要改状态
      if (nowdata) {
        let flows = nowdata.flows;
        for (let i = 0; i < flows.length; i++) {
          if (flows[i].isPaid) {
            state = false;
          }
        }
      }
      return state;
    },
   
    // 获取项目详情
    async getProjectGetInfo(id) {
      let result = await getProjectGetInfoApi({ id });
      if (result.code == 200) {
        return result.data;
      }
    },

    // 改变装DemandShow状态
    changeDemandShowFn() {
      this.demandShow = 0;
    },
    // 订单时间到了，刷新列表
    TimeIsUp() {
      // 状态为1时再发请求

      let timer = setTimeout(() => {
        this.getConsumptionapilistfn(true);

        clearTimeout(timer);
      }, 59000);
    },
    //查询用戶对应订单信息
    async getConsumptionapilistfn(isRefresh) {
      const _this = this,
        unpaidList = _this.unpaidList;
      // 未支付已经请求过就使用缓存
      if (unpaidList.length > 0 && this.ParamsObj.status == 1 && !isRefresh) {
        // 获取所剩时间
        unpaidList.forEach((item) => {
          createdTime = new Date(item.createdTime).getTime();
          // 十五分钟后结束
          createdTime += 1000 * 60 * 15;

          item.minutes = Math.floor(createdTime - Date.now());
        });
        _this.contractList = unpaidList;
        return;
      }
      //发送请求
      let { code, rows } = await getConsumptionapilist(this.ParamsObj);
      if (code != 200) return;
      // 定义变量
      let createdTime, result;
      // 状态为1时再查找且状态为1没有请求过
      if (this.ParamsObj.status == 1 && (unpaidList.length == 0 || isRefresh)) {
        // 获取所剩时间
        rows.forEach((item) => {
          createdTime = new Date(item.createdTime).getTime();
          createdTime += 1000 * 60 * 15;
          result = Math.floor(createdTime - Date.now());
          item.minutes = result;
        });
        _this.unpaidList = rows;
      }

      // 把type=14的问金转让过滤掉
      let newArr = rows.filter(item=>{
        return item.type != '14'
      })
      _this.contractList = newArr;
    },

    //查询对应ID订单信息
    async getConsumptionapilistinfofn(id) {
      let { code, data } = await getConsumptionapilistinfo({ id: id });
      if (code != 200) return;
      //给金额补00
      data.amount = this.$options.filters["sumFilters"](data.amount);
      const orderinfo = data;
      this.detailBoughtShow = data.type;
      this.demandShow = 1;
      let createdTime = new Date(data.createdTime).getTime();
      // let result = createdTime - data.presentTime;

      // let minutes = timestampConversion.getSeconds(result);
      createdTime = new Date(data.createdTime).getTime();
      createdTime += 1000 * 60 * 15;
      console.log(Math.floor(createdTime - Date.now()), "时间时间时间");
      // 获取所剩时间
      orderinfo.minutes = Math.floor(createdTime - Date.now());
      this.orderinfo = orderinfo;
      // console.log(this.orderinfo, "this.orderinfo");
      // this.$bus.$emit("father", data);
    },

    //订单搜索
    async searchinput() {
      this.unpaidList = [];
      this.getConsumptionapilistfn(false);
      //
      // let { code, rows } = await getConsumptionapilist({
      //   title: this.searchValue,
      // });
      // if (code != 200) return;
      // this.contractList = rows;
      // console.log(rows, "2222");
    },
    async rowclick(e) {
      // console.log(e,'lllllllllllllllllllllllllllll');
      this.currentActive = e.id;
      this.orderNo = e.id;
      // 获取项目的数据 -------------------- :project="project" :orderinfo="orderinfo" :step="step" :flow="flow"
      if(e.type=='6'){
        let nowdata = await this.getProjectGetInfo(e.goodsId);
        if (nowdata) {
          this.project = nowdata; //项目数据
          //根据no字段排序
          let arr = nowdata.flows.sort((a, b) => Number(a.no) - Number(b.no));
          this.step = arr; //步骤的数据
          // 获取当前要支付的步骤的数据
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].isPaid) {
              this.flow = arr[i + 1];
            }
          }
        }
      }

      await this.getConsumptionapilistinfofn(e.id);

      switch (this.payStatus) {
        case 1:
          if(e.type=='6'){
            let s = await this.isCountDown(e);
            this.projectIpaid = s;
          }
          this.demandShow = 1;
          // this.getConsumptionapilistinfofn(e.id);
          break;
        case 2:
          this.demandShow = 2;
          // this.getConsumptionapilistinfofn(e.id);
          if (e.type == 20 || e.type == 21) {
            this.demandShow = 5;
          }
          break;

        case 3:
          if (e.type == 5 || e.type == 6) {
            this.demandShow = 3;
          } else if (e.type == 20 || e.type == 21) {
            this.demandShow = 5;
          } else {
            this.demandShow = 4;
          }
          break;
      }
    },
    //结案的回调函数
     refreshclosOrder(){
      this.payStatus=3
      //隐藏父主键结案按钮
      this.$bus.$emit("closOrderstatus","0")
    },
     // 支付成功后的回调
    completePayFn() {
      // 改变购买状态
      this.$set(this.contractListinfo, "purchase", true);
      this.demandShow = 1;
      this.getscontractListinfofn(this.contractListinfo.id);
    },
    //待支付
    waitpay() {
      this.payStatus = 1;
      this.ParamsObj.status = 1;
      this.getConsumptionapilistfn(false);
    },
    //服务中
    service() {
      this.payStatus = 2;
      this.ParamsObj.status = "2,3";
      this.getConsumptionapilistfn(false);
    },
    //已完成
    Completed() {
      this.payStatus = 3;

      this.ParamsObj.status = 0;

      this.getConsumptionapilistfn(false);
    },
    //状态的展示
    selecttype(value) {
      const stateMap = {
        1: "法条",
        2: "解答",
        3: "政策",
        4: "合同",
        5: "咨询",
        6: "项目",
        20: "合同智审",
        21: "诉讼模拟",
        22: "阿米巴预算",
        23: "文控",
        24: "阿米巴预算试用",
        25: "税账医生",
      };
      return stateMap[value];
    },

    num(n) {
      return n < 10 ? "0" + n : "" + n;
    },
    countdown() {
      var _this = this;
      var time = window.setInterval(function () {
        if (_this.seconds === 0 && _this.minutes !== 0) {
          _this.seconds = 59;
          _this.minutes -= 1;
        } else if (_this.minutes === 0 && _this.seconds === 0) {
          _this.seconds = 0;
          window.clearInterval(time);
        } else {
          _this.seconds -= 1;
        }
      }, 1000);
    },

    //获取第一个汉字
    getHanzi(name) {
      if (name) {
        let arr = name.split("");
        let reg =
          /^(\d+$|[a-z]+$|[A-Z]+$|[` ~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]+$|((?=[!-~])[^\da-zA-Z])+$)/;
        let str = "";
        for (let i = 0; i < arr.length; i++) {
          if (!reg.test(arr[i])) {
            return arr[i];
          }
        }
      }
    },
  },
  //监听时间
  watch: {
    second: {
      handler(newVal) {
        this.num(newVal);
      },
    },
    minute: {
      handler(newVal) {
        this.num(newVal);
      },
    },
  },
  //计算时间
  computed: {
    second() {
      return this.num(this.seconds);
    },
    minute() {
      return this.num(this.minutes);
    },
  },
};
</script>

<style scoped>
/* 高度 */
::v-deep .label-box-content,
::v-deep .label-box-content .el-row,
::v-deep .label-box-content .el-col,
::v-deep .label-box-content .el-col > div,
::v-deep .label-box-content .el-card,
::v-deep .label-box-content .el-card__body {
  height: 100%;
}
::v-deep .label-box-content .el-card__body {
  position: relative;
  padding: 0 0 30px 0;
}
::v-deep .label-box-content .el-card__body > .top {
  margin: 0 30px;
}
::v-deep .label-box-content .el-card__body > div {
  height: 92%;
  overflow-y: auto;
}
::v-deep .label-box-content .el-card__body > div::-webkit-scrollbar {
  width: 0px;
}

::v-deep .FeaturedContent .el-card__body > div {
  padding: 0 30px;
}
::v-deep .pay .pay_main {
  padding: 0 30px;
}

ul,
p {
  list-style: none;
  margin: 0;
  padding: 0;
}
.pd30 {
  /* padding: 0 30px; */
}

/* 顶部搜索框 */
.top_search .el-input {
  width: 175px;
}
.top_search .el-input >>> input {
  height: 34px;
  line-height: 34px;
  border-radius: 20px;
}
.top_search .el-input .el-icon-search {
  cursor: pointer;
  font-size: 16px;
}

/* 一级 */
.tabOne {
  display: flex;
  justify-content: space-evenly;
  border: 1px solid #e5e6e9;
  background-color: #f9f9f9;
  border-radius: 12px;
  padding: 26px 0;
  margin-top: 15px;
  margin-left: 30px;
  margin-right: 30px;
}
.tabOne .tablist {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}
.tabOne .tablist img {
  width: 36px;
}
.tabOne .tablist img.imgsel {
  display: none;
}
.tabOne .tablist.isActive img.imgsel {
  display: block;
}
.tabOne .tablist.isActive img.imgnor {
  display: none;
}

.tabOne .tablist button {
  color: #686975;
  font-size: 16px;
  background-color: transparent;
  border: 2px solid #c8cce2;
  padding: 6px 20px;
  margin-top: 18px;
}
.tabOne .tablist::before {
  content: "";
  display: none;
  position: absolute;
  bottom: -26px;
  width: 0;
  height: 0;
  border-bottom: 12px solid #e5e6e9;
  border-top: 20px solid transparent;
  border-right: 20px solid transparent;
  border-left: 20px solid transparent;
}
.tabOne .tablist::after {
  content: "";
  display: none;
  position: absolute;
  bottom: -27px;
  width: 0;
  height: 0;
  border-bottom: 12px solid #fff;
  border-top: 20px solid transparent;
  border-right: 20px solid transparent;
  border-left: 20px solid transparent;
}

.tabOne .tablist.isActive button,
.tabOne .tablist button:hover {
  color: #fff;
  background-color: #6A769F;
  border-color: #6A769F;
}
.tabOne .tablist.isActive::before {
  display: block;
}
.tabOne .tablist.isActive::after {
  display: block;
}

/* 暂无数据样式 */
.forData {
  text-align: center;
  font-size: 14px;
  color: #ccc;
  margin: 30px 0;
}

/* 订单列表 */
.orderList ul {
  list-style: none;
  margin: 0;
  padding: 0;
  margin-top: 10px;
}
.orderList ul > li {
  position: relative;
  padding: 20px 30px 18px 30px;
  border-bottom: 1px solid #efefef;
  cursor: pointer;
}
.orderList ul > .active {
  background-color: #f4f5f8;
}
.orderList ul > li:hover {
  background-color: #f4f5f8;
}
.orderList ul > li > i {
  position: absolute;
  left: 30px;
  top: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  width: 30px;
  height: 30px;
  background-color: #38476d;
  border-radius: 4px;
  color: #fff;
  font-style: normal;
}
.orderList ul > li:nth-child(even) > i {
  background-color: #b1bedf;
}
.orderList ul > li > h2 {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  font-size: 16px;
  color: #333;
  margin: 0;
  padding-bottom: 12px;
}
.orderList ul > li > h2 > p {
  width: 75%;
  overflow: hidden; /*超出部分隐藏*/
  white-space: nowrap; /*不换行*/
  text-overflow: ellipsis; /*超出部分文字以...显示*/
}
.orderList ul > li > h2 > span {
  width: 25%;
  display: flex;
  justify-content: flex-end;
  text-align: right;
  font-weight: 400;
  color: #f87a23;
  font-size: 12px;
}
.orderList ul > li > h2 > span.isSerive {
  color: #39486f;
}
.orderList ul > li > h2 > span.isOk {
  color: #999;
}
.orderList ul > li .coll_des {
  width: 100%;
  font-size: 13px;
  line-height: 20px;
  margin: 0;
  color: #666;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}
.orderList ul > li .coll_source {
  margin: 0;
  line-height: 18px;
  font-size: 12px;
  color: #bbb;
}
.pay_main .inputTitle {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}
.pay_main .inputTitle span {
  font-size: 14px;
  color: #999;
  font-weight: 400;
}
::v-deep .pay_main .el-tabs__header {
  border: 0;
  margin-bottom: 24px;
}
::v-deep .pay_main .el-tabs__nav {
  width: 100%;
  display: flex;
  justify-content: space-between;
  border: 0;
}
::v-deep .pay_main .el-tabs__item {
  width: 49%;
  border-radius: 8px;
  text-align: center;
  font-size: 14px;
  font-weight: bold;
  border: 0;
  background-color: #fafafa;
}
::v-deep .pay_main .el-tabs__item.is-active {
  background-color: #f1f3ff;
  color: #39486f;
}
::v-deep .pay_main .el-tabs__item:hover {
  color: #39486f;
}

/* 内容详情列表 */
.detailList {
  border-bottom: 1px solid #ecedf0;
  padding-bottom: 15px;
  margin-bottom: 30px;
}
.detailList li {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
}
.detailList li > span {
  display: block;
  width: 17%;
  font-size: 14px;
  color: #999;
}
.detailList li .detailPage {
  width: 83%;
}
.detailList li .detailPage > p {
  width: 100%;
  font-size: 14px;
  color: #222;
}
/* 組件樣式衝突 */
>>> .featuredContent .el-card__body {
  padding: 0 30px;
}
>>> .featuredContent .el-card__body > .top {
  margin: 0;
}
</style>
